package com.beatingapp;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.modifier.PathModifier;
import org.andengine.entity.modifier.PathModifier.Path;
import org.andengine.entity.scene.IOnAreaTouchListener;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.ITouchArea;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.controller.MultiTouch;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.debug.Debug;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.Toast;


public class SonidoActivity extends SimpleBaseGameActivity implements IOnAreaTouchListener
{

	private final static int CAMERA_WIDTH = 800;

	private final static int CAMERA_HEIGHT = 480;	

	private Camera camera;	
	

	private BitmapTextureAtlas fondoTexture, mBitmapTextureAtlas, infoTextureAtlas;

	private ITextureRegion fondoTextureRegion, gritoTextureRegion, carroTextureRegion, personajeTextureRegion, reproductorTextureRegion, infoTextureRegion;

	private Sprite gritoSprite, carroSprite, reproductorSprite, personajeSprite;

	//private Text tiempoText;

	private Font font;

	private int tiempo = 10;

	private Sound gritoSound, carroSound, reproductorSound, silencioSound, grito2,carro2,reproductor2;
	
	private boolean grito, carro, reproductor ,personaje;

	private Scene scene, scenaInfo;
	
	private int salir = 0;
	
	private int iniciarpato,iniciarcarro, iniciartetera=0;
	
	private BitmapTextureAtlas BarraTiempoTextureAtlas;

	private ITextureRegion BarraTiempo;
	
	private Path Tiempo;
	private PathModifier pathModifier;
	private Sprite BarraSprite;

	@Override
	public EngineOptions onCreateEngineOptions( )
	{
		camera = new Camera( 0, 0, CAMERA_WIDTH, CAMERA_HEIGHT );
		EngineOptions engineOptions = new EngineOptions( true, ScreenOrientation.LANDSCAPE_SENSOR,
				new RatioResolutionPolicy( CAMERA_WIDTH, CAMERA_HEIGHT ), camera );
		engineOptions.getAudioOptions( ).setNeedsSound( true );
		engineOptions.getTouchOptions().setNeedsMultiTouch(true);
		if(MultiTouch.isSupported(this)) 
		{
			if(!MultiTouch.isSupportedDistinct(this)) 
			{
				Toast.makeText(this, "MultiTouch detectado, pero tiene problemas para distinguir entre dedos", Toast.LENGTH_SHORT).show();
			}
		} 
		else 
		{
			Toast.makeText(this, "Tu dispositivo no soporta multiTouch!\n", Toast.LENGTH_SHORT).show();
		}
		Toast.makeText( getApplicationContext(), "Toca los elemetos que produzcan ruido molesto\npara silenciarlos", Toast.LENGTH_SHORT ).show( );
		return engineOptions;
	}

	@Override
	protected void onCreateResources( )
	{
		BitmapTextureAtlasTextureRegionFactory.setAssetBasePath( "gfx/" );

		// cargando el fondo
		this.fondoTexture = new BitmapTextureAtlas( this.getTextureManager( ), 1024, 512 );
		this.fondoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.fondoTexture, this, "Fondo_Sonido (1).png", 0, 0 );
		this.fondoTexture.load( );

		this.mBitmapTextureAtlas = new BitmapTextureAtlas( this.getTextureManager( ), 1024, 512 );
		this.carroTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBitmapTextureAtlas, this, "Televisor.png", 50, 0);
		this.gritoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBitmapTextureAtlas, this, "Pato.png", 350, 170);
		this.reproductorTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBitmapTextureAtlas, this, "Tetera.png", 270, 70);
		this.mBitmapTextureAtlas.load();
		this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBitmapTextureAtlas, this, "Personaje2.png", 420, 60);
		this.mBitmapTextureAtlas.load();
		this.BarraTiempoTextureAtlas = new BitmapTextureAtlas( this.getTextureManager( ), 1024, 512 );
		BarraTiempo=BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.BarraTiempoTextureAtlas, this, "barra.png", 0, 0);
		this.BarraTiempoTextureAtlas.load();


		try
		{
			// cargando sonido colision
			SoundFactory.setAssetBasePath( "mfx/" );
			
			this.gritoSound = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"Cuak.mp3" );
			
			this.carroSound = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"Drama.mp3" );
			
			this.reproductorSound = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"Tetera1.wav" );
			this.silencioSound = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"silencio.mp3" );
			this.grito2 = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"Cuak.mp3" );
			
			this.carro2 = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"Drama.mp3" );
			
			this.reproductor2 = SoundFactory.createSoundFromAsset( this.getSoundManager( ), this, 
					"Tetera1.wav" );
			
			gritoSound.setLooping(true);
			carroSound.setLooping(true);
			reproductorSound.setLooping(true);
			grito2.setLooping(true);
			carro2.setLooping(true);
			reproductor2.setLooping(true);
			silencioSound.setLooping(true);

			//TODO cargar sonidos faltantes
		}
		catch ( IOException e )
		{
			Debug.e( e );
		}

		// cargando fuente
		this.font = FontFactory.create( this.getFontManager( ), this.getTextureManager( ), 256,
				256, Typeface.create( Typeface.DEFAULT, Typeface.BOLD ), 32 );
		this.font.load( );		
	}

	@Override
	protected Scene onCreateScene( )
	{
		grito = true;
		carro = true;
		reproductor = true;
		personaje= true;
		
		scene = new Scene( );
		scene.setBackgroundEnabled( false );
	//	tiempoText = new Text( 5, 5, this.font, tiempo + " seg", this.getVertexBufferObjectManager( ) );

		Sprite fondoSprite = new Sprite( 0, 0, fondoTextureRegion, new VertexBufferObjectManager( ) );
		gritoSprite = new Sprite( 40,195, gritoTextureRegion, new VertexBufferObjectManager( ) );
		carroSprite = new Sprite( 130,195, carroTextureRegion, new VertexBufferObjectManager( ) );
		reproductorSprite = new Sprite( 50,105, reproductorTextureRegion, new VertexBufferObjectManager( ) );
		personajeSprite = new Sprite( 420,60, personajeTextureRegion, new VertexBufferObjectManager( ) );
		BarraSprite = new Sprite (0,0, this.BarraTiempo, this.getVertexBufferObjectManager());
		Tiempo = new Path( 2 ).to(-800, 0).to(0, 0);		
		pathModifier = new PathModifier( 10f, Tiempo);
		BarraSprite.registerEntityModifier( pathModifier );			
		
		
		
		final Timer t = new Timer();  

		TimerTask task = new TimerTask() 
		{  

			@Override  
			public void run() 
			{  
				runOnUiThread(new Runnable() 
				{  

					@Override  
					public void run() 
					{  		      
						if (tiempo > 0)  
						{
								
							tiempo--;
							if( tiempo<9 && grito)
							{
								if(iniciarpato==0){
								gritoSound.play();	
								iniciarpato=1;
								cambiarImagen();
								}
								//tiempoText.setText("inicio el grito");
								
							}
							else if( tiempo<6 && carro )
							{
								if(iniciarcarro==0){
								carroSound.play();
								iniciarcarro=1;
								cambiarImagen();
								}
								
							
							}
							else if( tiempo<3 && reproductor)
							{
								if(iniciartetera==0){
								reproductorSound.play();
								iniciartetera=1;
								cambiarImagen();
								}
								
							}
							//tiempoText.setText(tiempo+" seg");
						}
						else
						{
							t.cancel();
							finalizarJuego();
						}
					}
				});  
			}  
		};  
		t.scheduleAtFixedRate(task, 0, 1000);

		scene.attachChild( fondoSprite );
		scene.attachChild( gritoSprite );
		scene.attachChild( carroSprite );
		scene.attachChild( reproductorSprite );
		scene.attachChild(personajeSprite);
		//scene.attachChild( tiempoText );
		scene.attachChild(BarraSprite);

		
		scene.registerTouchArea(gritoSprite);
		scene.registerTouchArea(carroSprite);
		scene.registerTouchArea(reproductorSprite);
		scene.setTouchAreaBindingOnActionDownEnabled(true);
		scene.setOnAreaTouchListener(this);

		return scene;
	}
	
	public void cambiarImagen(){
		this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				this.mBitmapTextureAtlas, this, "Personaje.png", 420, 60);
		this.mBitmapTextureAtlas.load();	
	}
	@Override
	public boolean onAreaTouched( TouchEvent arg0, ITouchArea arg1, float arg2, float arg3 )
	{
		if( tiempo > 0 )
		{
			
			if( arg0.isActionDown() )
			{
				
				
				if( arg1.equals(gritoSprite) )
				{
					grito = false;
					gritoSound.stop();
					gritoSound=silencioSound;
					this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
							this.mBitmapTextureAtlas, this, "Personaje2.png", 420, 60);
					this.mBitmapTextureAtlas.load();
					iniciarpato=2;
					
				}
				else if( arg1.equals(carroSprite) )
				{
					carro = false;
					carroSound.stop();
					carroSound=silencioSound;
					this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
							this.mBitmapTextureAtlas, this, "Personaje2.png", 420, 60);
					this.mBitmapTextureAtlas.load();
					iniciarcarro=2;
					
				}
				else if( arg1.equals(reproductorSprite) )
				{
					reproductor = false;
					reproductorSound.stop();
					reproductorSound=silencioSound;
					this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
							this.mBitmapTextureAtlas, this, "Personaje2.png", 420, 60);
					this.mBitmapTextureAtlas.load();
					iniciartetera=2;
				}
				return true;
			}
			else if( arg0.isActionUp() )
			{
				if( arg1.equals(gritoSprite) )
				{
					grito = true;
					iniciarpato=0;
						gritoSound= grito2;
					this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
							this.mBitmapTextureAtlas, this, "Personaje.png", 420, 60);
					this.mBitmapTextureAtlas.load();
					
				}
				else if( arg1.equals(carroSprite) )
				{
					carro = true;
					iniciarcarro=0;
					carroSound= carro2;
					this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
							this.mBitmapTextureAtlas, this, "Personaje.png", 420, 60);
					this.mBitmapTextureAtlas.load();
					
				}
				else if( arg1.equals(reproductorSprite) )
				{
					reproductor = true;
					iniciartetera=0;
					reproductorSound= reproductor2;
					this.personajeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(
							this.mBitmapTextureAtlas, this, "Personaje.png", 420, 60);
					this.mBitmapTextureAtlas.load();
					
				}
				
				return true;
			}
		}
		return false;
	}

	private void finalizarJuego() 
	{		
		gritoSound.stop();
		carroSound.stop();
		reproductorSound.stop();
		
		if( iniciarpato==2 && iniciarcarro==2 && iniciartetera==2 )
			crearEscenaFin( false );
		else
			crearEscenaFin( true );
	}  
	
	private void crearEscenaFin( final boolean pierde )
	{			
		String ruta ="fin.png";
		String msj = pierde ? "" : "";
		
		//msj += "\n(Toca la pantalla \npara salir)";
		
		Text texto = new Text( CAMERA_WIDTH /2, 25, this.font, msj, this.getVertexBufferObjectManager( ) );
		
		infoTextureAtlas = new BitmapTextureAtlas( getTextureManager( ), 800, 480 );
		infoTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset( 
				infoTextureAtlas, this, ruta, 0, 0 );
		infoTextureAtlas.load( );	
		
		
		scenaInfo = new Scene( );
		
		Sprite sprite = new Sprite( 0, 0, infoTextureRegion, new VertexBufferObjectManager( ));
		
		scenaInfo.attachChild( sprite );
		scenaInfo.attachChild( texto );
		
		
		Timer t = new Timer();  

		TimerTask task = new TimerTask() {  

			@Override  
			public void run() {  
				runOnUiThread(new Runnable() {  

					@Override  
					public void run() 
					{  		      
						if( salir == 0 )
						{
							Intent intent;
							if( !pierde )
							{
								BarraSprite.setVisible(false);
								intent = new Intent(SonidoActivity.this, IntroActivity.class);
								Bundle b = new Bundle( );
								b.putInt( "Actividad", 2 );
								b.putInt("Vidas", 3);
								intent.putExtras( b );
								startActivity(intent);
							}
							else
							{							
								BarraSprite.setVisible(false);
								intent = new Intent(SonidoActivity.this, IntroActivity.class);
								Bundle b = new Bundle( );
								b.putInt( "Actividad", 2 );
								b.putInt("Vidas", 2);
								intent.putExtras( b );
								startActivity(intent);
							}
							SonidoActivity.this.finish( );
							salir++;
						}
					}  
				});  
			}  
		};  

		t.scheduleAtFixedRate(task, 0, 1000);
	}
	
}
